package model

import (
	"errors"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"os"
	"github.com/go-xorm/core"
	"github.com/ngaut/log"
)

var MainDB *xorm.Engine

// 初始化数据库信息
func InitMainDB(dsn string, logOn bool, logFile string) error {
	var err error
	MainDB, err = xorm.NewEngine("mysql", dsn)
	if err != nil {
		return errors.New(fmt.Sprintf("database init error, msg: %s", err.Error()))
	}
	MainDB.SetMaxIdleConns(0)
	MainDB.SetMaxOpenConns(200)
	MainDB.SetConnMaxLifetime(0)

	log.Infof("database log config, log_on: %v, log_file: %v", logOn, logFile)
	if logOn {
		f, err := os.Create(logFile)
		if err != nil {
			panic(err.Error())
			return err
		}
		MainDB.ShowSQL(true)
		MainDB.Logger().SetLevel(core.LOG_INFO)
		MainDB.SetLogger(xorm.NewSimpleLogger(f))
	}

	return nil
}
